package com.zzb.framework.mail;

import com.zzb.framework.cache.CacheComponent;
import com.zzb.framework.param.service.SysParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * 邮件防火墙
 * Created by zhangzhenbin on 17-7-18.
 */
@Component
public class SendEmailFirewall {
    private static final String EMAIL_TOS_SUBJECT = "EMAIL_TOS_SUBJECT";
    @Autowired
    private CacheComponent cacheComponent;
    @Autowired
    private SysParamService sysParamService;
    //同一个用户没小时针对同一个SUBJECT最多发多少邮件

    public void filter(String to ,MimeMessage mimeMessage) throws Exception {
        Integer hoursSendNumber = sysParamService.get("HOURS_SEND_NUMBER", Integer.class, 3);
        String subject = mimeMessage.getSubject();
        Integer sendNumber = cacheComponent.get(EMAIL_TOS_SUBJECT, to + "_" + subject, Integer.class);
        //如果用户同一个小时针对同一个SUBJECT发邮件次数过多，则不能再发
        if (sendNumber != null && sendNumber > hoursSendNumber) {
            throw new Exception("用户同一个小时针对同一个SUBJECT发邮件次数超过[" + hoursSendNumber + "]次，则不能再发");
        }
        if (sendNumber == null) sendNumber = 0;
        sendNumber++;
        cacheComponent.put(EMAIL_TOS_SUBJECT, to + "_" + subject, sendNumber, 3600L);
    }
}
